package com.glodon.paas.search.resource;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.dozer.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.glodon.paas.document.api.bean.File;
import com.glodon.paas.search.listener.IndexListener;
import com.glodon.paas.search.model.DocumentEvent;
import com.glodon.paas.search.model.EventType;
import com.glodon.paas.search.model.HitFiles;
import com.glodon.paas.search.model.IndexDocument;
import com.glodon.paas.search.model.QueryDocument;
import com.glodon.paas.search.query.QueryService;
import com.glodon.paas.search.util.SearchConstants;
import com.sun.jersey.api.core.InjectParam;

@Component
@Path("/internal/file")
public class DocumentResource {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    @Qualifier("documentListener")
    private IndexListener listener;

    @Autowired
    @Qualifier("documentQueryService")
    private QueryService<IndexDocument, QueryDocument> docQueryService;

    @Autowired
    private Mapper dozerMapper;

    @PUT
    @Path("/{fileId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response onNotify(@PathParam("fileId") String fileId, @QueryParam("userId") String userId,
            @QueryParam("event") String event) {
        logger.info("received document notify, fileId:{}, userId:{}, evnet:{}", fileId, userId, event);
        EventType eventType = EventType.from(event);
        if (eventType == null) {
            eventType = EventType.UPLOAD;
        }
        DocumentEvent dEvent = new DocumentEvent(fileId, userId, null, eventType);
        listener.onEvent(dEvent);
        return Response.ok("{\"result\":\"success\"}").build();
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response searchFile(@InjectParam QueryDocument file) {
        logger.debug("document search:{}", file);
        HitFiles<IndexDocument> hitFiles = docQueryService.query(SearchConstants.INDEX_PAAS, SearchConstants.TYPE_DOC,
                file);
        List<File> files = new ArrayList<File>();
        Iterator<IndexDocument> iterator = hitFiles.getHits().iterator();
        while (iterator.hasNext()) {
            IndexDocument indexDoc = (IndexDocument) iterator.next();
            File docFile = dozerMapper.map(indexDoc, File.class);
            files.add(docFile);
        }
        return Response.ok(files, MediaType.APPLICATION_JSON).build();
    }
}
